package com.gking.resourcePool.service.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gking.resourcePool.common.BaseContext;
import com.gking.resourcePool.common.Result;
import com.gking.resourcePool.entity.Project;
import com.gking.resourcePool.entity.ProjectGroup;
import com.gking.resourcePool.entity.Resource;
import com.gking.resourcePool.mapper.ResourceMapper;
import com.gking.resourcePool.service.Project.ProjectService;
import com.gking.resourcePool.service.ProjectGroup.ProjectGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)//三级缓存解决bean循环注入问题
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ProjectGroupService projectGroupService;

    /**
     * 资源批量上传
     *
     * @param projectId 项目id
     * @param groupId   项目分组id
     * @param resources 上传的资源列表
     * @return s
     */
    @Transactional
    @Override
    public Result<String> uploadResources(String projectId, String groupId, List<MultipartFile> resources) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getId, projectId);
        queryWrapper.eq(Project::getIsDelete, 0);
        queryWrapper.eq(Project::getUserId, BaseContext.getCurrentId());
        if (projectService.getOne(queryWrapper) == null) return Result.error("项目不存在");

        if (groupId != null && groupId != "") {
            LambdaQueryWrapper<ProjectGroup> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProjectGroup::getIsDelete, 0);
            wrapper.eq(ProjectGroup::getProjectId, projectId);
            wrapper.eq(ProjectGroup::getUserId, BaseContext.getCurrentId());
            wrapper.eq(ProjectGroup::getId, groupId);
            if (projectGroupService.getOne(wrapper) == null) return Result.error("项目分组不存在");
        }

        String targetPath = "/www/resource/ResourcePool/" + projectId + "/";
        File targetDir = new File(targetPath);
        boolean exists = targetDir.exists();
        if (!exists) {
            boolean mkdir = targetDir.mkdirs();
            if (!mkdir) return Result.error("创建文件夹失败");
        }

        List<Resource> resourceList = resources.stream().map(file -> {
            String originalFilename = file.getOriginalFilename();
            String contentType = file.getContentType();
            long size = file.getSize();
            assert originalFilename != null;
            String[] hz = originalFilename.split("\\.");
            log.info("上传的文件的原始名称为：{}", originalFilename);
            log.info("上传的文件的类型为：{}", contentType);
            log.info("上传的文件的大小为：{}", size);
            log.info("长度：{}", hz.length);
            log.info("后缀：{}", hz[hz.length - 1]);

            String fileName = UUID.randomUUID() + "." + hz[hz.length - 1];

            try {
                file.transferTo(new File(targetPath + fileName));
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }

            Resource resource = new Resource();
            resource.setUserId(BaseContext.getCurrentId());
            resource.setFilename(fileName);
            resource.setOriginName(originalFilename);
            resource.setType(contentType);
            resource.setSize(String.valueOf(size));
            resource.setPath("/public/" + projectId + "/" + fileName);
            resource.setProjectId(projectId);
            if (groupId != null && groupId != "") resource.setGroupId(groupId);
            return resource;
        }).collect(Collectors.toList());

        this.saveBatch(resourceList);
        return Result.success("上传成功！");
    }

    /**
     * 修改资源分组
     *
     * @param resourceId 资源id
     * @param projectId  项目id
     * @param groupId    分组id
     * @return s
     */
    @Override
    public Result<String> changeResourceGroup(String resourceId, String projectId, String groupId) {
        LambdaQueryWrapper<ProjectGroup> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(ProjectGroup::getIsDelete, 0);
        wrapper1.eq(ProjectGroup::getProjectId, projectId);
        wrapper1.eq(ProjectGroup::getUserId, BaseContext.getCurrentId());
        wrapper1.eq(ProjectGroup::getId, groupId);
        if (projectGroupService.getOne(wrapper1) == null) return Result.error("项目分组不存在");

        LambdaUpdateWrapper<Resource> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Resource::getId, resourceId);
        wrapper.eq(Resource::getProjectId, projectId);
        wrapper.eq(Resource::getIsDelete, 0);
        wrapper.eq(Resource::getUserId, BaseContext.getCurrentId());
        wrapper.set(Resource::getGroupId, groupId);
        this.update(wrapper);

        return Result.success("修改资源分组成功！");
    }

    /**
     * 批量删除资源
     *
     * @param resourceIds 资源 id 列表
     * @return s
     */
    @Override
    public Result<String> deleteResources(List<String> resourceIds) {
        LambdaUpdateWrapper<Resource> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(Resource::getId, resourceIds);
        wrapper.eq(Resource::getUserId, BaseContext.getCurrentId());
        wrapper.eq(Resource::getIsDelete, 0);
        wrapper.set(Resource::getIsDelete, 1);
        wrapper.set(Resource::getDeleteTime, LocalDateTime.now());
        wrapper.set(Resource::getDeleteUserId, BaseContext.getCurrentId());
        this.update(wrapper);

        return Result.success("批量删除资源成功！");
    }

    /**
     * 分页获取资源列表
     *
     * @param projectId 项目id
     * @param groupId   分组id
     * @param size      分页大小
     * @param page      分页页码
     * @return l
     */
    @Override
    public Result<Page> getResources(String projectId, String groupId, Integer size, Integer page) {
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Resource::getProjectId, projectId);
        wrapper.eq(Resource::getIsDelete, 0);
        wrapper.eq(Resource::getUserId, BaseContext.getCurrentId());
        wrapper.orderByDesc(Resource::getCreateTime);
        if (groupId != null && groupId != "") wrapper.eq(Resource::getGroupId, groupId);

        Page<Resource> pageInfo = new Page<>(page, size);
        Page<Resource> pageResult = this.page(pageInfo, wrapper);

        for(Resource resource : pageResult.getRecords()){
            resource.setPath("http://115.190.202.175/resourcePool" + resource.getPath());
        }

        return Result.success("分页获取资源成功", pageResult);
    }


    /**
     * 获取删除资源列表
     *
     * @param size 分页大小
     * @param page 分页页码
     * @return l
     */
    @Override
    public Result<Page> getDeleteResources(Integer size, Integer page) {
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Resource::getIsDelete, 1);
        wrapper.eq(Resource::getUserId, BaseContext.getCurrentId());

        Page<Resource> pageInfo = new Page<>(page, size);
        Page<Resource> pageResult = this.page(pageInfo, wrapper);

        return Result.success("分页获取删除资源列表成功", pageResult);
    }

    /**
     * 恢复资源
     *
     * @param resourceIds 要恢复的资源 id 列表
     * @return s
     */
    @Transactional
    @Override
    public Result<String> recoverResources(List<String> resourceIds) {
        for (String resourceId : resourceIds) {
            Resource resource = this.getById(resourceId);
            if (resource == null) return Result.error("有资源不存在");

            LambdaUpdateWrapper<Project> projectWrapper = new LambdaUpdateWrapper<>();
            projectWrapper.eq(Project::getId, resource.getProjectId());
            projectWrapper.eq(Project::getUserId, BaseContext.getCurrentId());
            projectWrapper.eq(Project::getIsDelete, 1);
            projectWrapper.set(Project::getIsDelete, 0);

            LambdaUpdateWrapper<ProjectGroup> groupWrapper = new LambdaUpdateWrapper<>();
            groupWrapper.eq(ProjectGroup::getId, resource.getGroupId());
            groupWrapper.eq(ProjectGroup::getUserId, BaseContext.getCurrentId());
            groupWrapper.eq(ProjectGroup::getIsDelete, 1);
            groupWrapper.set(ProjectGroup::getIsDelete, 0);

            LambdaUpdateWrapper<Resource> resourceWrapper = new LambdaUpdateWrapper<>();
            resourceWrapper.eq(Resource::getId, resourceId);
            resourceWrapper.eq(Resource::getUserId, BaseContext.getCurrentId());
            resourceWrapper.eq(Resource::getIsDelete, 1);
            resourceWrapper.set(Resource::getIsDelete, 0);


            projectService.update(projectWrapper);
            projectGroupService.update(groupWrapper);
            this.update(resourceWrapper);
        }
        return Result.success("恢复成功！");
    }
}
